package gouhuo.allbugs.top.controller;

import gouhuo.allbugs.top.common.BaseResponse;
import gouhuo.allbugs.top.common.BusinessException;
import gouhuo.allbugs.top.common.ErrorCode;
import gouhuo.allbugs.top.model.request.visitor.VisitorAddRequest;
import gouhuo.allbugs.top.model.request.visitor.VisitorMsgAddRequest;
import gouhuo.allbugs.top.model.vo.UserVO;
import gouhuo.allbugs.top.service.VisitorService;
import gouhuo.allbugs.top.utils.ResultUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

import static gouhuo.allbugs.top.constant.RedisConstants.VISITOR_SET_SIMPLE_KEY;

/**
 * 访客
 */
@RestController
@RequestMapping("/visitor")
public class visitorController {

    @Resource
    private VisitorService visitorService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @ApiOperation("添加访客记录")
    @PostMapping("/add")
    public BaseResponse<Integer> addVisitor(@RequestBody VisitorAddRequest visitorAddRequest) {
        if (visitorAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean add = visitorService.addVisitor(visitorAddRequest);
        if (!add) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "访问失败");
        }
        return ResultUtil.success(200);
    }

    @ApiOperation("添加留言记录")
    @PostMapping("/msg")
    public BaseResponse<Integer> addVisitor(@RequestBody VisitorMsgAddRequest visitorMsgAddRequest) {
        if (visitorMsgAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        visitorService.addVisitorMsg(visitorMsgAddRequest);
        return ResultUtil.success(200);
    }

    @ApiOperation("查询前五名访客的头像")
    @GetMapping("/simple")
    public BaseResponse<List<Object>> visitorSimple(@RequestParam("userId") Integer userId) {
        if (userId == null || userId == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String simpleKey = VISITOR_SET_SIMPLE_KEY + userId;
        List<Object> list = stringRedisTemplate.opsForHash().values(simpleKey);
        return ResultUtil.success(list);
    }

    @ApiOperation("查询历史访客列表")
    @GetMapping("/full")
    public BaseResponse<List<UserVO>> visitorFull(@RequestParam("userId") Integer userId) {
        if (userId == null || userId == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<UserVO> list = visitorService.visitorFull(userId);
        return ResultUtil.success(list);
    }
}
